import { useRequestUserChannelsQuery } from "@service/channel";
import styles from "@pages/home/widgets/channel/styles/styles.module.less";
import classNames from "classnames";
import useChannelScroll from "@pages/home/channel/common/scroll";
import { useRef, useEffect } from "react";
import { useParams } from "react-router-dom";

export default function UserChannel() {

    // 获取路由参数
    const { cid } = useParams();
    const { data } = useRequestUserChannelsQuery(undefined);


    // 实现频道列表的滚动效果
    const { scrollHandler, scrollContainerRef } = useChannelScroll();
    // 判断频道列表是否获取成功, 如果没有成功暂时什么都不渲染

    // 用于存储所有频道列表的 DOM 对象
    const userChannelsDOM = useRef<Record<number, HTMLDivElement>>({});

    // 检测 cid 是否变化
    useEffect(() => {
        // 如果 cid 变化
        if (scrollContainerRef.current != null && typeof cid !== "undefined") {
            // 设置滚动位置
            scrollHandler(userChannelsDOM.current[Number(cid)]);
        }
    }, [cid, scrollHandler, scrollContainerRef]);
    if (typeof data === "undefined") return null;
    // 频道列表获取成功, 渲染视图


    return (
        <div className={styles.list} ref={scrollContainerRef}>
            {data.data.channels.map((channel) => (
                <div
                    key={channel.id}
                    ref={(el) => {
                        if (el) userChannelsDOM.current[channel.id] = el;
                    }}
                    className={classNames(styles.item, {
                        [styles.active]: channel.id === Number(cid),
                    })}
                    onClick={(event) => scrollHandler(event.currentTarget)}
                >
                    {channel.name}
                </div>
            ))}
        </div>
    );
}